<?php
//header( 'Content-Type:text/html;charset=utf-8 ');
use Workerman\Worker;

require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/vendor/autoload.php';

$db = new Workerman\MySQL\Connection('127.0.0.1', '3306', '', '', 'worker');

$worKer = new Worker("websocket://0.0.0.0:2019");
$worKer->count = 1;

$worKer->onConnect = function ($connection) {
    userLoginServerLog($connection);
};
$worKer->onMessage = function ($connection, $data) {
    $userData = json_decode($data);
    switch ($userData->type) {
        case 'login':
            userLogin($userData->name, $userData->pwd, $connection);
            break;
        case 'register':
            userRegister($userData->name, $userData->pwd, $connection);
            break;
        case 'senduserall';
            sendMessageAll($userData->message, $userData->name);
            break;
        case 'sendusersingle':
            sendMessageSingle($userData->userid, $userData->message);
            break;
        case 'useraddfriend':
            userAddFriends($userData->userid, $userData->friendid);
            break;
        case 'userlist':
            userlist($userData->userid);
            break;
        case 'userfriendsear':
            userFriendSear($userData->userid, $userData->name);
            break;
        case 'usersear':
            userSear($userData->name);
            break;
        default:
            return "Please submit the correct type operation!!!";
    }
};
$worKer->onClose = function ($connection) {
    userLogoutLog($connection);
};

//发送消息给指定用户
function sendMessageSingle($user, $message)
{
    global $worKer;
    var_dump("正在发送".$user);
    if (isset($worKer->connections[$user])) {
        $conn = $worKer->connections[$user];
        $datamess["message"] = $message;
        $datamess["type"] = "send";
        $data = json_encode($datamess, JSON_UNESCAPED_UNICODE);
        $conn->send($data);
    }
}

//发送消息给所有用户
function sendMessageAll($message, $name)
{
    global $worKer;
    foreach ($worKer->connections as $user) {
        $array = array();
        $array["name"] = $name;
        $array["mes"] = $message;
        $array["type"] = "senduserall";
        $data = json_encode($array, JSON_UNESCAPED_UNICODE);
        $user->send($data);
    }
}

//用户注册
function userRegister($name, $pwd, $connection)
{
    global $db;
    $select_id = $db->select('*')->from('wm_user')->where("userName= '$name' ")->single();
    if (!$select_id) {
        $db->insert('wm_user')->cols(array('userName' => $name, 'userPsswd' => $pwd, 'userIp' => $connection->getRemoteIp(),))->query();
    }
    var_dump("User has successfully registered!!!");
}

//用户登录
function userLogin($name, $pwd, $connection)
{
    global $db;
    $select_id = $db->select('userName,userId')->from('wm_user')->where("userName= '$name'", "userPsswd= '$pwd'")->row();
    $connection->uid = $select_id["userId"];
    if (!$select_id)
        var_dump("User does not exist, please register first");
    //插入登录记录表
    $user_ip = $connection->getRemoteIp();
    if ($select_id) {
        userLoginLog($user_ip, $name);
        $userlist = userList($select_id["userId"]);
        $select_id["type"] = "login";
        $select_id["userlist"] = $userlist;
        $data = json_encode($select_id, JSON_UNESCAPED_UNICODE);
        $connection->send($data);
    } else {
        var_dump("Login failed!!!");
    }

}

//用户登录记录
function userLoginLog($ip, $name)
{
    global $db;
    $db->insert('wm_login_log')->cols(array('loginIp' => $ip, 'loginName' => $name,))->query();
    var_dump("Successful login account!!!");
}

//用户退出记录
function userLogoutLog($connection)
{
    global $db, $worKer;
    $user_ip = $connection->getRemoteIp();
    $db->insert('wm_logout_log')->cols(array('logoutIp' => $user_ip, 'logoutName' => $connection->uid))->query();
    if (isset($connection->uid)) {
        unset($worKer->connection[$connection->uid]);
    }
    var_dump("Successful exit from account!!!");
}

//用户连接服务器记录
function userLoginServerLog($connection)
{
    global $db;
    $user_ip = $connection->getRemoteIp();
    $db->insert('wm_login_server')->cols(array('userIp' => $user_ip,))->query();
    var_dump("Successful connection to server!!!");
}

//用户添加好友
function userAddFriends($userid, $userFriid)
{
    global $db;
    $addinsertid = $db->select("*")->from("wm_user_friend")->where("userId= '$userid'")->single();
    if (!$addinsertid) {
        $db->insert('wm_user_friend')->cols(array('userId' => $userid, 'userFriendId' => $userFriid))->query();
    } else {
        $db->update("wm_user_friend")->where("userId= '$userid'")->cols(array('userFriendId' => $userFriid))->query();
    }
    var_dump("Success in Adding Friends!!");
}

//用户好友列表
function userList($userid)
{
    global $db;
    $userfriendlist = $db->select("userFriendId")->from("wm_user_friend")->where("userId= '$userid'")->row();
    $list = "(" . $userfriendlist["userFriendId"] . ")";
    $userlist = $db->query("SELECT `UserName`,`UserId` FROM `wm_user` WHERE `userId` in $list");
    return $userlist;
}

//用户好友搜索
//function userFriendSear($userid, $name)
//{
//    global $db;
//    $userfriendlist = $db->select("userFriendId")->from("wm_user_friend")->where("userId= '$userid'")->row();
//    $list = "(" . $userfriendlist["userFriendId"] . ")";
//    $userlist = $db->query("SELECT * FROM `wm_user` WHERE userId IN $list AND userName LIKE  '%$name%'");
//    var_dump($userlist);
//}

//搜索用户
function userSear($name)
{
    global $db;
    $userlist = $db->query("SELECT * FROM `wm_user` WHERE userName LIKE  '%$name%'");
    var_dump($userlist);
}

//前台页面搭建
$webman = new \Workerman\WebServer("http://0.0.0.0:2346");
$webman->addRoot("", "/mnt/hgfs/gonew/workerman");
// 运行worker
Worker::runAll();